package com.cy.store.service.impl;

import com.cy.store.entity.Address;
import com.cy.store.mapper.AddressMapper;
import com.cy.store.service.BaseService;
import com.cy.store.service.IAddressService;
import com.cy.store.service.IDistrictService;
import com.cy.store.service.ex.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-12-05 15:42
 */

/**
 * 收货地址的业务层实现类
 */
@Slf4j
@Service
public class AddressServiceImpl  extends BaseService implements IAddressService{
    /**
     * 用户可声明的最大的地址数
     */
    @Value("${user.address.max-count}")
    private int maxCount;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private IDistrictService districtService;

    /**
     * 新增收货地址
     * @param uid 用户id
     * @param username 用户名
     * @param address 用户添加的地址信息
     */
    @Override
    public void addNewAddress(Integer uid, String username, Address address) {
        // 调用收货地址统计方法
        Integer count = addressMapper.countByUid(uid);

        // 如果地址数量已经到了最大值则抛出异常
        if (count >= maxCount){
            throw new AddressCountLimitException(COUNT_ERROR_MESSAGE);
        }
        // 对address对象中的数据进行补全：省市区
        address.setProvinceName(districtService.getNameByCode(address.getProvinceCode()));
        address.setCityName(districtService.getNameByCode(address.getCityCode()));
        address.setAreaName(districtService.getNameByCode(address.getAreaCode()));

        // 补充uid和isDefault
        address.setUid(uid);
        address.setIsDefault(count == 0 ? 1 : 0);


        // 补全日志信息
        updateService(address,username,INSERT_DATA);

        // 执行插入方法
        Integer rows = addressMapper.insert(address);
        if (!rows.equals(1)){
            throw new InsertException(INSERT_ERROR_MESSAGE);
        }
    }

    /**
     * 根据用户id获取用户地址信息
     * @param uid 用户id
     * @return 用户地址信息
     */
    @Override
    public List<Address> getByUid(Integer uid) {
        List<Address> list = addressMapper.findByUid(uid);
        if (list.isEmpty()){
            return null;
        }

        // 只返回前端需要的数据，提高交互性能
        list.stream().map((item) ->{
            item.setUid(null);
            item.setProvinceCode(null);
            item.setCityCode(null);
            item.setAreaCode(null);
            item.setCreatedUser(null);
            item.setCreatedTime(null);
            item.setModifiedUser(null);
            item.setModifiedTime(null);
            return item;
        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 根据aid修改某个用户的默认收货地址
     * @param aid 收货地址id
     * @param uid 用户的id
     * @param username 用户名
     */
    @Override
    public void setDefault(Integer aid, Integer uid, String username) {
        Address result = addressMapper.findByAid(aid);

        // 检测当前要修改的收货地址是否存在
        if (isNull(result)){
            throw new AddressNotFoundException(ADDRESS_NOTFOUND_MESSAGE);
        }

        // 检测当前获取到的收货地址数据的归属
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException(ACCESS_DENIED_MESSAGE);
        }

        // 将所有的收货地址设置为非默认
        Integer rows = addressMapper.updateNoneDefaultByUid(uid);
        if (rows < 1){
            throw new UpdateException(UPDATE_ERROR_MESSAGE);
        }

        // 将用户选中的地址设置为默认地址
        rows = addressMapper.updateDefaultByAid(aid, username, new Date());
        if (!rows.equals(1)){
            throw new UpdateException(UPDATE_ERROR_MESSAGE);
        }

    }

    /**
     * 根据aid删除地址
     * @param aid 地址id
     * @param uid 用户id
     * @param username 用户名
     */
    @Override
    public void deleteByAid(Integer aid, Integer uid, String username) {
        // 判断数据的存在与归属
        Address result = addressMapper.findByAid(aid);
        if (isNull(result)){
            throw new AddressNotFoundException(ADDRESS_NOTFOUND_MESSAGE);
        }
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException(ACCESS_DENIED_MESSAGE);
        }

        // 调用持久层方法删除地址信息
        Integer rows = addressMapper.deleteByAid(aid);
        if (!rows.equals(1)){
            throw new DeleteException(DELETE_ERROR_MESSAGE);
        }

        // 如果删除的是唯一的数据就直接返回
        Integer count = addressMapper.countByUid(uid);
        if (count.equals(0)){
            // 直接返回
            return;
        }

        // 查询当前数据是否为默认数据
        if (!result.getIsDefault().equals(1)){
            // 直接返回
            return;
        }

        // 获取最后一次修改的地址数据并修改为默认地址
        Address lastAddress = addressMapper.findLastModified(uid);
        rows = addressMapper.updateDefaultByAid(lastAddress.getAid(), username, new Date());
        if (!rows.equals(1)){
            throw new UpdateException(UPDATE_ERROR_MESSAGE);
        }

    }

    /**
     * 根据aid获取地址信息
     * @param aid 地址id
     * @return 地址信息
     */
    @Override
    public Address getByAid(Integer aid) {
        // 调用持久层方法
        Address result = addressMapper.findByAid(aid);

        // 返回前端页面要展示的address对象
        if (!isNull(result)){
            result.setAid(null);
            result.setUid(null);
            result.setIsDefault(null);
            result.setCreatedUser(null);
            result.setModifiedUser(null);
            result.setCreatedTime(null);
            result.setModifiedTime(null);
            return result;
        }
        return null;
    }

    /**
     * 根据aid修改用户地址
     * @param address 地址信息
     * @param uid 用户id
     * @param username 用户名
     */
    @Override
    public void updateByAid(Address address, Integer uid, String username) {
        // 如果前端传来的address对象为null直接返回
        if (isNull(address)){
            return;
        }

        // 判断当前收货地址的归属
        Address result = addressMapper.findByAid(address.getAid());
        if (!result.getUid().equals(uid)){
            throw new AccessDeniedException(ACCESS_DENIED_MESSAGE);
        }

        // 对address对象中的数据进行补全：省市区
        address.setProvinceName(districtService.getNameByCode(address.getProvinceCode()));
        address.setCityName(districtService.getNameByCode(address.getCityCode()));
        address.setAreaName(districtService.getNameByCode(address.getAreaCode()));

        // 更新日志信息
        updateService(address,username,UPDATE_DATA);

        // 调用持久层方法修改地址信息，并判断是否执行成功
        Integer rows = addressMapper.updateByAid(address);
        if (!rows.equals(1)){
            throw new UpdateException(UPDATE_ERROR_MESSAGE);
        }
    }

    /**
     * 根据收货地址数据的id，查询收货地址详情
     * @param aid 收货地址id
     * @param uid 归属的用户id
     * @return 匹配的收货地址详情
     */
    @Override
    public Address getByAid(Integer aid, Integer uid) {
        // 根据收货地址数据id，查询收货地址详情
        Address address = addressMapper.findByAid(aid);

        // 地址信息不存在
        if (isNull(address)) {
            throw new AddressNotFoundException(ADDRESS_NOTFOUND_MESSAGE);
        }

        // 非法访问
        if (!address.getUid().equals(uid)) {
            throw new AccessDeniedException(ACCESS_DENIED_MESSAGE);
        }

        address.setProvinceCode(null);
        address.setCityCode(null);
        address.setAreaCode(null);
        address.setCreatedUser(null);
        address.setCreatedTime(null);
        address.setModifiedUser(null);
        address.setModifiedTime(null);
        return address;
    }
}
